//
//  HMHomeViewController.swift
//  HMWeibo12
//
//  Created by iOS on 16/9/16.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit
import SVProgressHUD
import SVPullToRefresh

private let originalIdentifier = "originalIdentifier"
private let retweetIdentifier = "retweetIdentifier"

class HMHomeViewController: HMBaseViewController {
    
    var statusVMs: [HMStatusVM]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    /// 下拉刷新控件
    private var pullDownRefreshView: HMPullDownRefreshView = HMPullDownRefreshView()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isUserLogin {
            return
        }
        
        // 只有登录后才需要做后面的事情
        setupTabelView()
        
        setupNavigationBar()
        
        print("HMHomeViewController self: \(self)")
        
        // 显示FPS
//        UIApplication.shared.keyWindow?.showInCenter()
    }
    
    private func setupTabelView() {
        tableView.register(UINib(nibName: "HMStatusCell", bundle: nil), forCellReuseIdentifier: originalIdentifier)
        tableView.register(UINib(nibName: "HMRetweetStatusCell", bundle: nil), forCellReuseIdentifier: retweetIdentifier)
        // 设置tableView的预估行号
//        tableView.estimatedRowHeight = 200
        // 行高根据cell的约束自动计算
//        tableView.rowHeight = UITableViewAutomaticDimension
        // 去除cell分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        
        // 刷新控件添加到tableView
        tableView.addSubview(pullDownRefreshView)
        
        // 设置刷新控件进入刷新后的闭包
        pullDownRefreshView.refreshingCallback = { () -> Void in
            // 加载新数据
            self.loadNewStatus()
        }
        
        // 主动进入刷新,需要注意有进入刷新的回调闭包
        pullDownRefreshView.beginRefreshing()
        
//        // 上拉加载控件
//        tableView.addInfiniteScrolling { 
//            // 加载更多数据
//            self.loadMoreStatus()
//        }
    }
    
    private func loadMoreStatus() {
        let max_id = statusVMs?.last?.status.id ?? 0
        
        HMHMStatusListVM.shared.loadStatuses(since_id: 0, max_id: max_id) { (statusVMs: [HMStatusVM]?, error: Error?) in
            // 结束上拉加载
            self.tableView.infiniteScrollingView.stopAnimating()
            
            // 判断是否有错误
            if error != nil {
                print("上拉加载更多微博出错了: \(error)")
                return
            }
            
            let count = statusVMs?.count ?? 0
            if count == 0 {
                print("上拉没有加载到数据")
                return
            }
            
            print("上拉加载到 \(count) 条数据")
            // 上拉加载到的更多微博数据要拼接到现有数据后面
            self.statusVMs = self.statusVMs! + statusVMs!
        }
    }
    
    /// 加载新的微博数据
    private func loadNewStatus() {
        // 获取到id最大的微博
        let since_id = statusVMs?.first?.status.id ?? 0
        
        HMHMStatusListVM.shared.loadStatuses(since_id: since_id, max_id: 0) { (statusVM: [HMStatusVM]?, error: Error?) in
            self.pullDownRefreshView.endRefreshing()
            
            // 判断是否有错误
            if error != nil {
                print("下拉刷新微博出错了: \(error)")
                return
            }
            
            let count = statusVM?.count ?? 0
            
            // 只有下拉刷新才需要显示
            if since_id > 0 {
                self.showTipLabel(count: count)
            }
            
            if count == 0 {
                print("没有加载到数据")
                return
            }
            
            if since_id > 0 {
                // 下拉刷新,新数据要拼接在现有数据前面
                self.statusVMs = statusVM! + self.statusVMs!
                print("下拉刷新 加载到微博数据: \(count)")
            } else {
                // 程序第一次运行
                self.statusVMs = statusVM
                print("程序第一次运行 加载到微博数据: \(count)")
                
                // 上拉加载控件
                self.tableView.addInfiniteScrolling {
                    // 加载更多数据
                    self.loadMoreStatus()
                }
            }
        }
    }
    
    // 显示下拉微博数量提示
    private func showTipLabel(count: Int) {
        // animationKeys != nil, 说明有动画正在执行,不在添加动画了
        if let animationKeys = tipLabel.layer.animationKeys() {
            print("animationKeys: \(animationKeys)")
            return
        }
        
        containerView.isHidden = false
        let countString = count == 0 ? "没有新的微博" : "加载到了 \(count) 条微博"
        
        tipLabel.text = countString
        
        UIView.animate(withDuration: 0.75, animations: {
            // UIView动画重复执行
//            UIView.setAnimationRepeatCount(5)
            
            // UIView动画反过来执行
//            UIView.setAnimationRepeatAutoreverses(true)
            self.tipLabel.frame.origin.y = 0
            }) { (_) in
//                print("结束了")
                // 返回的动画
                UIView.animate(withDuration: 0.75, delay: 0.75, options: [], animations: { 
                    self.tipLabel.frame.origin.y = -HMHomeTipLabelHeight
                    }, completion: { (_) in
//                        print("真的结束了")
                        self.containerView.isHidden = true
                })
        }
    }
    
    private func setupNavigationBar() {
        let name = HMUserAccountVM.shared.userAccount?.screen_name
        
        // 标题按钮
        let button = HMHomeTitleButton(name: name)
        button.addTarget(self, action: #selector(titleButtonClick(button:)), for: .touchDown)
        self.navigationItem.titleView = button
        // 方案4
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
    }
    
    // MARK: - 按钮点击事件
    func titleButtonClick(button: UIButton) -> Void {
        // 切换状态
        button.isSelected = !button.isSelected
        
        let transfrom = button.isSelected ? CGAffineTransform(rotationAngle: CGFloat(M_PI - 0.001)) : CGAffineTransform.identity
        
        UIView.animate(withDuration: 0.25) { 
            button.imageView?.transform = transfrom
        }
    }
    
    // MARK: - 懒加载
    /// 下拉刷新提示的label
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        
        // 设置
        label.backgroundColor = UIColor.orange
        label.textColor = UIColor.white
        label.font = UIFont.systemFont(ofSize: 16)
        label.textAlignment = NSTextAlignment.center
        label.text = "没有新的微博"
        
        label.frame = CGRect(x: 0, y: -HMHomeTipLabelHeight, width: UIScreen.width, height: HMHomeTipLabelHeight)
        self.containerView.addSubview(label)
        
//        self.navigationController?.navigationBar.insertSubview(label, at: 0)
        
        return label
    }()
    
    private lazy var containerView: UIView = {
        let view = UIView()
        
//        view.backgroundColor = UIColor.brown
        // 超出边界的都剪掉
        view.clipsToBounds = true
        view.frame = CGRect(x: 0, y: HMHomeTipLabelHeight, width: UIScreen.width, height: HMHomeTipLabelHeight)
        view.isHidden = true
        self.navigationController?.navigationBar.addSubview(view)
        
        return view
    }()
}

extension HMHomeViewController {
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        print("indexPath - \(indexPath)")
        let statusVM = self.statusVMs![indexPath.row]
        
//        print("indexPath: \(indexPath), rowHeight = \(statusVM.rowHeight)")
        return statusVM.rowHeight
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusVMs?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let statusVM = self.statusVMs![indexPath.row]
        
        // 原创微博拿原创微博的xib, 转发微博拿转发微博的xib
        let cellId = statusVM.isRetweetedStatus ? retweetIdentifier : originalIdentifier
//        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HMStatusCell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId) as! HMStatusCell
        
        // 简单设置cell内容
        cell.statusVM = statusVM
        
        return cell
    }

    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        print("tableView滚动了: \(scrollView.contentOffset.y)")
        // 根据tableView的滚动,设置刷新控件的状态
        // 在这边处理好不好?
    }
}
